package cn.com.majiang.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.ShardedJedis;

/**
 * Redis 缓存
 * 
 */
public class RedisUtil {
    public static final String TAG = RedisUtil.class.getSimpleName();

    static Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    /**
     * 私有构造器.
     */
    private RedisUtil() {
    }

    //定义Jedis连接池对象变量
    private static JedisPool pool = null;

    /**ujujs * 构建redis连接池
     * 
     * @param
     * @param
     * @return JedisPool
     */
    public  static JedisPool getPool() {
        if (pool == null) {
            JedisPoolConfig config = new JedisPoolConfig();
            //控制一个pool可分配多少个jedis实例，通过pool.getResource()来获取；
            //如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
            config.setMaxActive(1000);
            //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
            config.setMaxIdle(500);
            //表示当borrow(引入)一个jedis实例时，最大的等待时间，如果超过等待时间，则直接抛出JedisConnectionException；
            config.setMaxWait(1000 * 100);
            //在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
            config.setTestOnBorrow(true);
            //加载redis服务器配置信息
            String redisHost = PropertyPlaceholder.getProperty("redisHost");
            String redisPort = PropertyPlaceholder.getProperty("redisPort");
            String redisPass = PropertyPlaceholder.getProperty("redisPass");
            pool = new JedisPool(config, redisHost, Integer.parseInt(redisPort),2000,redisPass);
            logger.info("redis服务器IP:" + redisHost + ", 端口:" + redisPort);
        }
        return pool;
    }

    /**
     * 返还到连接池
     * 
     * @param pool
     * @param redis
     */
    public static void returnResource(JedisPool pool, Jedis redis) {
        if (redis != null) {
            pool.returnResource(redis);
        }
    }

    /**
     * 获取数据
     * 
     * @param key
     * @return
     */
    public static boolean exists(String key) {
        ShardedJedis jedis = null;
        try {
            boolean result = jedis.exists(key);
            return result;
        } catch (Exception e) {
            return false;
        }
    }
    public static String getJedisValue(String redisKey) {
    	String value = "";
    	JedisPool pool = null;
        Jedis jedis = null;
        try {
            pool = new RedisUtil().getPool();
            jedis = pool.getResource();
            value = jedis.get(redisKey);
            logger.info(TAG + "-》当前key为{},值为{}",redisKey,value);
        }
        catch (Exception e) {
            //释放redis对象
            pool.returnBrokenResource(jedis);
            logger.error("=================获取Jedis连接报错：" + e.getStackTrace());
            e.printStackTrace();
            return value;
        }
        finally {
           //返还到连接池
            returnResource(pool, jedis);
        }
        return value;
    }

    /**
     * 保存数据
     * @param key
     * @return
     */
    public static void setJedisValue(String key, int expires, String value) {
    	JedisPool pool = null;
        Jedis jedis = null;
        try {
            pool = getPool();
            jedis = pool.getResource();
            jedis.set(key, value);
            jedis.expire(key,expires);
        }
        catch (Exception e) {
            //释放redis对象
            pool.returnBrokenResource(jedis);
            logger.error("=================获取Jedis连接报错：" + e.getStackTrace());
            e.printStackTrace();
        }
        finally {
           //返还到连接池
            returnResource(pool, jedis);
        }
    }

    /**
     * 保存数据
     * @param key
     * @return
     */
    public static void setJedisValue(String key, String value) {
        JedisPool pool = null;
        Jedis jedis = null;
        try {
            pool = getPool();
            jedis = pool.getResource();
            jedis.set(key, value);
        }
        catch (Exception e) {
            //释放redis对象
            pool.returnBrokenResource(jedis);
            logger.error("=================获取Jedis连接报错：" + e.getStackTrace());
            e.printStackTrace();
        }
        finally {
            //返还到连接池
            returnResource(pool, jedis);
        }
    }

    /**
     * 获取jedis对象
     * @return
     */
    public static Jedis getJedis() {
        JedisPool pool = null;
        Jedis jedis = null;
        try {
            pool = getPool();
            jedis = pool.getResource();
            return jedis;
        }
        catch (Exception e) {
            //释放redis对象
            pool.returnBrokenResource(jedis);
            logger.error("=================获取Jedis连接报错：" + e.getStackTrace());
            e.printStackTrace();
        }
        finally {
            //返还到连接池
            returnResource(pool, jedis);
        }
        return null;
    }

    public static void delJedisValue(String key) {
        JedisPool pool = null;
        Jedis jedis = null;
        try {
            pool = getPool();
            jedis = pool.getResource();
            jedis.del(key);
        }
        catch (Exception e) {
            //释放redis对象
            pool.returnBrokenResource(jedis);
            logger.error("=================获取Jedis连接报错：" + e.getStackTrace());
            e.printStackTrace();
        }
        finally {
            //返还到连接池
            returnResource(pool, jedis);
        }
    }
    /**
     * 主方法测试
     * 
     * @param args
     */
    public static void main(String[] args) {
        //Jedis jedis = RedisUtil.getJedis();
        //        long start = System.currentTimeMillis();  
        //        Long result = 0l;
        //        for (int i = 0; i < 5; i++) {  
        //            result = jedis.lpush("list1", "n" + i);  
        //            System.out.println(result);  
        //        }  
        //        System.out.println("xx="+jedis.lrange("list1", 0, -1));  
        //        long end = System.currentTimeMillis();  
        //        System.out.println("Simple SET: " + ((end - start)/1000.0) + " seconds");  
        //        jedis.disconnect();  

        //logger.info("=============jedis keys=" + jedis.keys("*"));
        //logger.info("===============sismember1=" + jedis.sismember("yrdAsTermSet", "yrd/getUserInfoRequest"));
       String code = "FC6M";
       /* RedisUtil.setJedisValue("12", new Long(RedisConstant.EXPIRES_ONE_DAY).intValue(),
                "121" );*/
       String value = RedisUtil.getJedisValue("12");
        System.out.println("cacheExist"+value);
        if(!code.equals(value)){
            System.out.println("11111111111111111");
        }
        String s = null;
        s.equals("aa");
    }
}
